package net.entelijan.cobean.filesel;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FilesystemFileselDAO implements IFileselDAO {

	private static final int EOF = 65535;
	private static Log log = LogFactory.getLog(FilesystemFileselDAO.class);

	public FilesystemFileselDAO() {
		super();
	}

	public Collection<String> loadProposals(String id) {
		ArrayList<String> re = new ArrayList<String>();
		File persDir = getAndCreatePersistantDir();
		File persFile = new File(persDir, id);
		if (persFile.exists()) {
			try {
				loadProposals(re, persFile);
			} catch (IOException e) {
				log.error(
						"Could not load proposals because: " + e.getMessage(),
						e);
			}
		}
		return re;
	}

	private void loadProposals(ArrayList<String> re, File persFile)
			throws IOException {
		String content = readFileToString(persFile);
		String[] props = content.split(",");
		for (String prop : props) {
			re.add(prop);
		}
	}

	public void saveProposals(String id, Collection<String> proposals) {
		try {
			StringBuilder sb = new StringBuilder();
			int cnt = 0;
			for (String prop : proposals) {
				if (cnt++ > 0) {
					sb.append(",");
				}
				sb.append(prop);
			}
			File persDir = getAndCreatePersistantDir();
			File persFile = new File(persDir, id);
			writeStringToFile(persFile, sb.toString());
		} catch (Exception e) {
			log.error("Could not save proposals because: " + e.getMessage(), e);
		}
	}

	private File getAndCreatePersistantDir() {
		File homeDir = new File(System.getProperty("user.home"));
		if (!homeDir.exists()) {
			throw new IllegalStateException(
					"Cannot access the user's home directory " + homeDir);
		}
		File compDir = new File(homeDir, ".org.entelijan.components");
		if (!compDir.exists()) {
			boolean ok = compDir.mkdirs();
			if (!ok) {
				throw new IllegalStateException("Could not create directory '"
						+ compDir + "'");
			}
		}
		File fileselDir = new File(compDir, "filesel");
		if (!fileselDir.exists()) {
			boolean ok = fileselDir.mkdirs();
			if (!ok) {
				throw new IllegalStateException("Could not create directory '"
						+ fileselDir + "'");
			}
		}
		return fileselDir;
	}

	private void writeStringToFile(File file, String value) {
		try {
			PrintWriter pw = null;
			try {
				pw = new PrintWriter(file);
				pw.print(value);
			} finally {
				if (pw != null) {
					pw.close();
				}
			}
		} catch (IOException e) {
			throw new IllegalStateException("Could not write '" + value
					+ "' to " + file + " because: " + e.getMessage());
		}

	}

	private String readFileToString(File file) {
		try {
			FileReader fr = null;
			StringBuilder sb = new StringBuilder();
			try {
				fr = new FileReader(file);
				char c = (char) fr.read();
				while (c != EOF) {
					sb.append(c);
					c = (char) fr.read();
				}
				return sb.toString();
			} finally {
				if (fr != null) {
					fr.close();
				}
			}
		} catch (IOException e) {
			throw new IllegalStateException("Could not read " + file
					+ " because: " + e.getMessage());
		}
	}

}
